package com.vgooo.util;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.Log;

import com.vgooo.client.R;
import com.vgooo.client.VGApplication;

public class AsyncImageLoader extends
		AsyncTask<ImageLoaderTask, String, Bitmap> {

//	private ImageView imageView;
//	private View view ;
//	private boolean isImageView ;
	private boolean hasHandler ;
//	private HashMap<String, BitmapRef> caches = VGApplication
//			.getCaches();
	private String imageCachesPath = VGApplication.cachesPath + "/images/";
//	private String urlPath;
	
	private ImageLoaderTask loaderTask  ;

	public AsyncImageLoader() {
		super();
	}
	
	

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		if(hasHandler){
			BitmapUtils.sendLoading(loaderTask.handler);
		}
	}



	@Override
	protected Bitmap doInBackground(ImageLoaderTask... params) {
		// TODO Auto-generated method stub
		loaderTask = params[0];
//		InputStream inputStream = null ;
		byte[] data  = null ;
		Bitmap bm = null ;
		Options opts = null ;
		try {
//			inputStream = HttpUtils.getStream(loaderTask.urlPath, null,
//					HttpUtils.METHOD_GET);
			data = HttpUtils.getBytes(loaderTask.urlPath, null, HttpUtils.METHOD_GET);
			publishProgress("从网络路径" + loaderTask.urlPath + "获取字符流成功");
			opts = new Options();
			opts.inJustDecodeBounds = true;
			bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
			int x = 0 ,y = 0;
			if(loaderTask.isImgeView){
				if(loaderTask.imageView.getWidth()==0||loaderTask.imageView.getHeight()==0){
					x = 1 ;
					y = 1 ;
				}else{
					x = opts.outWidth / loaderTask.imageView.getMeasuredWidth();
					y = opts.outHeight / loaderTask.imageView.getMeasuredHeight();
				}
			}else{
				x = opts.outWidth / loaderTask.view.getWidth();
				y = opts.outHeight / loaderTask.view.getHeight();
			}
			int scale = x > y ? x : y;
			bm = BitmapUtils.getBitmap(data, scale);
//			 bm = BitmapUtils.getBitmap(inputStream);
			if (bm != null) {
				publishProgress("从网络路径" + loaderTask.urlPath + "获取网络图片成功");
				try {// 将下载好的图片保存到缓存中
					BitmapUtils.save(loaderTask.urlPath, bm);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					UmengUtils.onError(loaderTask.context, "缓存图片失败："+e.toString());
				}
				return bm;
			} else {
				
				String str = "获取" + loaderTask.urlPath + "网络图片失败" ;
				publishProgress(str);
				UmengUtils.onError(loaderTask.context, str);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			publishProgress("Exception = " + e.getMessage());
			e.printStackTrace();
			UmengUtils.onError(loaderTask.context, e.toString());
		}catch(Exception e2){
			Log.i("AsyncImageLoader(Java:110)", loaderTask.urlPath+e2);
			e2.printStackTrace();
			UmengUtils.onError(loaderTask.context, loaderTask.urlPath+e2);
		}
		
		finally{
			if(data!=null){
				data = null ;
			}
			if(opts!=null){
				opts = null ;
			}
//			System.gc();
			
//			if(inputStream!=null){
//				try {
//					inputStream.close();
//				} catch (Exception e2) {
//					e2.printStackTrace() ;
//					UmengUtils.onError(loaderTask.context, e2.toString());
//				}
//			}
		}
		return null;
	}

	@Override
	protected void onProgressUpdate(String... values) {
		// TODO Auto-generated method stub
		log(values[0]);
		super.onProgressUpdate(values);
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		// TODO Auto-generated method stub
		// caches.put(urlPath, new SoftReference<Bitmap>(result));
		
		if (result != null) {
			if(hasHandler){
				BitmapUtils.sendLoadSuccess(loaderTask.handler);
			}
//			imageView.setImageBitmap(result);
			setBitmap(loaderTask, result);
		}else{
			if(hasHandler){
				BitmapUtils.sendLoadFail(loaderTask.handler);
			}
//			imageView.setBackgroundResource(R.drawable.image_default);
			setBitmap(loaderTask);
		}
		super.onPostExecute(result);
	}

	private void log(String info) {
//		Log.i(this.getClass().getSimpleName(), info);
		DebugTools.log(this.getClass().getSimpleName(), info) ;
	}
	
	
	private static void setBitmap(ImageLoaderTask loaderTask , Bitmap bm){
		if(loaderTask.isImgeView){
			loaderTask.imageView.setImageBitmap(bm);
		}else{
			loaderTask.view.setBackgroundDrawable(new BitmapDrawable(bm));
		}
		
		bm = null ;
	}
	private static void setBitmap(ImageLoaderTask loaderTask ){
		if(loaderTask.isImgeView){
//			loaderTask.imageView.setBackgroundResource(R.drawable.image_default);
			loaderTask.imageView.setImageResource(R.drawable.image_default);
		}else{
			loaderTask.view.setBackgroundResource(R.drawable.image_default);
		}
	}

}
